package com.sciener.control;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sciener.entity.UploadHeaderData;
import com.sciener.service.UserService;

public class uploadPhotoServlet extends HttpServlet{
	
	private static UserService userservice = new UserService();


	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userid;
		String headerpath = null;
		String type;
		try{
			String photoRootPath = request.getSession().getServletContext().getRealPath("");
			InputStream is = request.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			Object obj = ois.readObject();
			UploadHeaderData uploadheaderdata = (UploadHeaderData)obj;
			
			userid  = uploadheaderdata.getUserid();
			
			int index = uploadheaderdata.getIndex();
			type = uploadheaderdata.getType();
			String photoPath = null;
			String filename;
			String filepath = null;
			if(type.equals("header"))
			{
				photoPath =photoRootPath + "/header" + File.separator + userid;
				filename = userid+".jpg";
				filepath = photoPath + File.separator + filename;
				headerpath = "/header" + File.separator + userid + File.separator + filename;
			}
			else if(type.endsWith("car"))
			{
				photoPath =photoRootPath + "/carphoto" + File.separator + userid;
				filename = "photo"+index+".jpg";
				filepath = photoPath + File.separator + filename;
			}
			else if(type.endsWith("licence"))
			{
				photoPath =photoRootPath + "/licence" + File.separator + userid;
				filename = "licence"+index+".jpg";
				filepath = photoPath + File.separator + filename;
			}
			
			File file = new File(photoPath);
			System.out.println(file.getAbsolutePath());
			if(!file.exists())
			{
				file.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(filepath);
			fos.write(uploadheaderdata.getPhotoData());
			fos.close();
		}catch (Exception e) {
			e.printStackTrace();
			response.getWriter().println("fail");
			return;
		}
		try {
			if(type.equals("header"))
			{
				userservice.updateHeaderbyid(userid,headerpath);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().println("fail");
			return;
		}
		response.getWriter().println("success");
		
	}
	
	

}
